#!/bin/bash
set -e
set -o pipefail

# 获取脚本路径
current_dir=$(cd $(dirname $0); pwd)
# 导入公共方法
source ${current_dir}/common.sh
# 导入配置文件
source ${current_dir}/config.cnf

# pgbackrest 相关目录
pgbackrest_log_dir=/var/log/pgbackrest
pgbackrest_config_dir=/etc/pgbackrest


# 配置备份归档工具
function pg_backup_install_pgbackrest(){
    # 创建pgbackrest相关目录
    mkdir -p -m 770 ${pgbackrest_log_dir}
    mkdir -p ${pgbackrest_config_dir}
    touch ${pgbackrest_config_dir}/pgbackrest.conf
    chmod 640 ${pgbackrest_config_dir}/pgbackrest.conf
    chown -R postgres:postgres ${pgbackrest_log_dir}
    chown -R postgres:postgres ${pgbackrest_config_dir}/pgbackrest.conf

    # 备份存放路径
    mkdir -p ${pg_backupdir}
    chmod 750 ${pg_backupdir}
    chown -R postgres:postgres ${pg_backupdir}

    # 拷贝已编译好的pgbackrest
    if [ ! -f "/usr/bin/pgbackrest" ]; then
        cp ${current_dir}/${backup_tool} /usr/bin/pgbackrest
        chmod +x /usr/bin/pgbackrest
        chown postgres:postgres /usr/bin/pgbackrest

        cp ${current_dir}/backup_pgbackrest.sh ${pg_backupdir}
        chmod +x ${pg_backupdir}/backup_pgbackrest.sh
        chown postgres:postgres ${pg_backupdir}/backup_pgbackrest.sh

        # 替换固定脚本信息
        sed -i "s/^stanza=.*/stanza=${bak_stanza_name}/g" ${pg_backupdir}/backup_pgbackrest.sh
        sed -i "s/^task_interval=.*/task_interval='${bak_task_interval}'/g" ${pg_backupdir}/backup_pgbackrest.sh
        sed -i "s%^pg_backupdir=.*%pg_backupdir='${pg_backupdir}'%g" ${pg_backupdir}/backup_pgbackrest.sh
    fi

    # 配置pgbackrest
    echo -e "
[${bak_stanza_name}]
pg1-path=${pg_datadir}
pg1-port=${pg_port}

[global]
repo1-path=${pg_backupdir}
# 保留3个完整的备份
repo1-retention-full=${bak_fullbackup_save_num}
# 备份快速启动
start-fast=y
# 可以启用并行来加快速度，但执行备份阶段一般不需要（因为可能CPU不足的话会影响数据库服务器性能），执行恢复阶段可以考虑打开（恢复阶段PG已关闭）
# process-max=3

[global:archive-push]
compress-level=3" > /etc/pgbackrest/pgbackrest.conf

}

# 配置 pgbackrest，创建存储空间、检查、配置定时任务
function pg_backup_pgbackrest_set(){
    local check_master_or_slave=$(su - postgres -c "psql -c 'select pg_is_in_recovery();'"|grep t|wc -l)
    if [ $check_master_or_slave -eq 0 ];then
        # 创建存储空间
        #su - postgres -c "pgbackrest --stanza=${bak_stanza_name} --log-level-console=info stanza-create"
        # 检查配置
        #su - postgres -c "pgbackrest --stanza=${bak_stanza_name} --log-level-console=info check"
        comm_print_note "创建存储空间..."
        ${pg_backupdir}/backup_pgbackrest.sh "create"
        comm_print_note "备份检查..."
        ${pg_backupdir}/backup_pgbackrest.sh "check"
        comm_print_note "设置定时备份..."
        ${pg_backupdir}/backup_pgbackrest.sh "add_crontab"
    else
        comm_print_note "当前实例为从库，无需创建备份空间。"
    fi
}

# 配置pg归档命令，使用pgbackrest进行归档
function pg_backup_pgbackrest_set_archive_mode(){
    sed -i "s/^archive_command = ''.*$/archive_command = 'pgbackrest --stanza=${bak_stanza_name} archive-push %p'/" ${pg_datadir}/postgresql.conf
    su - postgres -c "psql -c \"SELECT pg_reload_conf();\""
}

function deploy_pgbackrest(){
    comm_print_note "部署安装 pgbackrest"
    pg_backup_install_pgbackrest
    comm_print_note "配置pg归档命令archive_command，使用pgbackrest进行归档"
    pg_backup_pgbackrest_set_archive_mode
    comm_print_note "配置 pgbackrest，创建存储空间、检查、配置定时任务"
    pg_backup_pgbackrest_set
}

# 卸载pgbackrest，同步会删除文件，也就是删除本机上的所有备份
function uninstall_pgbackrest(){
    comm_print_note "卸载pgbackrest"
    rm -f /usr/bin/pgbackrest
    comm_print_note "删除数据目录： ${pgbackrest_log_dir} |  ${pg_backupdir}  |  ${pgbackrest_config_dir} | /tmp/pgbackrest"
    rm -rf ${pgbackrest_log_dir} ${pg_backupdir} ${pgbackrest_config_dir} /tmp/pgbackrest
    comm_print_note "删除 crontab 定时备份任务"
    sed -i '/backup_pgbackrest.sh/d' /etc/crontab
}

# # 使用说明
usage () {
        cat <<EOF
Usage: $0 [OPTIONS]
  install                    部署安装 pgbackrest
  set_archive_mode           配置归档参数，修改PG的postgresql.conf
  create_check               配置 pgbackrest，创建存储空间、检查、配置定时任务
  deploy                     部署完整的 pgbackrest，包括创建存储空间、检查、配置定时任务
  uninstall                  卸载备份，同时删除定时任务与备份文件          
EOF
exit
}

# main 入口
command="${1}"
case "${command}" in
    "install" )
        comm_print_note "仅安装 pgbackrest"
        pg_backup_install_pgbackrest
    ;;
    "set_archive_mode" )
        comm_print_note "配置pg归档命令archive_command，使用pgbackrest进行归档"
        pg_backup_pgbackrest_set_archive_mode
    ;;
    "create_check" )  
	    comm_print_note "配置 pgbackrest，创建存储空间、检查、配置定时任务"
        pg_backup_pgbackrest_set
    ;;
    "deploy" )  
	    comm_print_note "部署完整的 pgbackrest，包括创建存储空间、检查、配置定时任务"
        deploy_pgbackrest
    ;;
    "uninstall" )  
	    uninstall_pgbackrest
    ;;
    * )
        usage
    ;;
esac